<template>
  <div class="accountRenewal">
    <div class="accountRenewal_containner">
      <div class="accountRenewal_containner_left">
        <div class="account_title_ids">
          <div class="account_title_top">
            <div class="account_tips">
              {{
                groupId === 0
                  ? settingsStore.platformInfo.appname
                  : roleName +
                    '(' +
                    mobile.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') +
                    ')'
              }}
            </div>
            <div class="national" v-if="!groupId">{{ extractedText }}</div>
          </div>
          <div class="account_title_bottom">
            <span v-if="!groupId" class="idCope"
              >ID:{{ settingsStore.platformInfo.LongStoreId
              }}<CopyDocument
                @click="cope"
                style="margin-left: 5px; cursor: pointer"
                class="cope"
            /></span>
            <span>系统将于{{ day }}天后过期</span>
            <span
              @click="renewBtn"
              style="
                color: var(--primary-color);
                cursor: pointer;
                margin-left: 5px;
              "
              >续费</span
            >
          </div>
        </div>
        <div class="account_province">
          <div class="account_province_left">
            <div class="province_box">
              <span class="province_pismmtion">开通省份</span>
              <el-select
                v-model="province"
                :placeholder="firstCity"
                style="width: 60px"
              >
                <el-option
                  disabled
                  v-for="item in provinceCity"
                  :key="item.id"
                  :label="item.provinceName"
                  :value="item.id"
                />
              </el-select>
              <span class="province_num" style="margin-left: 20px">{{
                provinceCity.length ?? 0
              }}</span>
            </div>
            <div class="defalt" v-if="defaultProvince">
              默认省份
              <span class="infos">{{ defaultProvince[0].provinceName }}</span>
            </div>
          </div>
          <div class="account_province_left" v-if="!groupId && coverName">
            <div class="province_box">
              <span class="province_pismmtion" @click="juamRouter">账号数</span>
              <span class="province_num">{{ max_account_num }}</span>
            </div>
            <div class="defalt">
              已使用
              <span class="infos" style="color: var(--primary-color)">{{
                freeNum
              }}</span>
            </div>
          </div>
          <div class="account_province_left">
            <div class="province_box">
              <span class="province_pismmtion"
                >余额(元)
                <View
                  v-if="isShow"
                  @click="view"
                  style="width: 1em; height: 1em; cursor: pointer" /><Hide
                  v-else
                  @click="view"
                  style="width: 1em; height: 1em; cursor: pointer"
              /></span>
              <span
                class="infos"
                style="
                  color: var(--primary-color);
                  cursor: pointer;
                  font-size: 14px;
                "
                @click="juemClick"
                >充值</span
              >
            </div>
            <div class="defalt" style="color: #000; margin-top: 6px">
              {{ isShow ? storeBalance : '****' }}
            </div>
          </div>
          <div
            class="account_province_left icon"
            style="border-right: none; text-align: center"
          >
            <a
              :href="entranceUrl.pc"
              style="margin-right: 20px"
              v-if="entranceUrl.pc"
            >
              <div class="bg">
                <i class="iconfont icon-diannao_o"></i>
              </div>
              <p class="font">电脑</p>
            </a>
            <a
              :href="entranceUrl.h5"
              style="margin-right: 20px"
              v-if="entranceUrl.h5"
            >
              <div class="bg">
                <i class="iconfont icon-shouji-copy"></i>
              </div>
              <p class="font">手机</p>
            </a>
            <a href="javascript:void(0);" class="xcx" v-if="entranceUrl.xcx">
              <div class="bg">
                <i class="iconfont icon-xiaochengxu"></i>
              </div>
              <p class="font">小程序</p>
              <div class="qrCode">
                <QrcodeGenerator
                  :text="entranceUrl.xcx"
                  :size="150"
                  :logoUrl="entranceUrl.logoUrl"
                  level="H"
                  style="z-index: 9933; position: absolute"
                  class="code-box"
                />
              </div>
            </a>
          </div>
        </div>
        <div class="account_url_device"></div>
      </div>
      <div class="accountRenewal_containner_right">
        <el-button class="upgrade" @click="jumpTo" v-if="groupId == 0"
          >升级</el-button
        >
      </div>
    </div>
  </div>
  <!-- 弹框 -->
  <Dialog
    title="扫码支付"
    v-model="dialogTableVisible"
    width="500"
    @closeIcon="closeIcon"
  >
    <template #center>
      <div class="qrcode" v-loading="imgLoading">
        <img :src="code_url" alt="" class="qrImage" />
        <p>{{ goodsName }}</p>
        <p v-if="timeRemaining > 0">{{ formattedTime }}</p>
        <p v-else>刷新页面重新支付</p>
      </div>
    </template>
  </Dialog>
</template>
<script setup>
// 前端生成二维码组件
import { getIndexPlatformInfo } from '@/api/appv2/appv2.js';
import QrcodeGenerator from '@/components/QrcodeGenerator/index.vue';
import Dialog from '@/components/payDialog/index.vue';
import QRCode from 'qrcode';
import useSettingsStore from '@/store/modules/settings';
import { ElMessage } from 'element-plus';
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getProvince } from '@/api/leader/Filling.js';
import { accountList } from '@/api/system/account.js';
import withdraw from '@/modules';
const { accountBalanceApi, codeRenewalApi, channelRenewalVertiyApi } = withdraw;
const router = useRouter();
const settingsStore = useSettingsStore();
const imgLoading = ref(false);
const dialogTableVisible = ref(false);
const storeId = ref('');
const storeBalance = ref('');
const provinceCity = ref([]);
const firstCity = ref('');
const province = ref('');
const defaultProvince = ref('');
const isShow = ref(false);
const max_account_num = ref('');
const freeNum = ref('');
const timeRemaining = ref(300); // 倒计时时间，单位：秒（5 分钟）
const code_url = ref('');
const out_trade_no = ref('');
const goodsName = ref('');
const paymentStatus = ref(''); // 支付状态：空、success、failed
const pageData = ref({
  page: 1,
  pageSize: 10,
});
const entranceUrl = computed(() => settingsStore.entranceUrl);
const { groupId, mobile, id, roleName } = JSON.parse(
  localStorage.getItem('userDateInfo') || {}
);
storeId.value = JSON.parse(
  localStorage.getItem('userDateInfo')
    ? localStorage.getItem('userDateInfo')
    : {}
)?.storeId;
//
const getInfo = async () => {
  const res = await getIndexPlatformInfo();
  settingsStore.setPlatformInfo(res);
};
// 判断是否包含A2
const coverName = computed(() => {
  const str2 = 'A2';
  return roleName.includes(str2);
});
const day = computed(() => {
  // 当前日期
  const currentDate = new Date();
  if (isNaN(new Date(settingsStore.platformInfo.expiredate_time).getTime())) {
    console.error('createTime 无效，请检查格式！');
    return 0;
  }
  // 目标日期
  const targetDate = new Date(settingsStore.platformInfo.expiredate_time);

  // 计算相差的天数
  const timeDifference = targetDate - currentDate;
  const daysUntilExpiry = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));

  return daysUntilExpiry;
});
const extractedText = computed(() => {
  const match = settingsStore.platformInfo.appname.match(/（(.*?)）/); // 匹配括号内的内容
  return match ? match[1] : ''; // 返回括号里的文字
});
// 复制
async function cope() {
  try {
    await navigator.clipboard.writeText(id.value);
    ElMessage.success('复制成功');
  } catch (err) {
    console.log('err:', err);
    ElMessage.error('复制成功');
  }
}
//账户余额
const getUserMoney = async () => {
  try {
    const { data } = await accountBalanceApi();
    storeBalance.value = data.storeBalance;
  } catch (error) {
    console.log('error:', error);
  }
};
const view = () => {
  isShow.value = !isShow.value;
};
const juemClick = () => {
  router.push({ path: '/financialMan/rechargeManage' });
};
const juamRouter = () => {
  router.push({ path: '/system/userDate' });
};
const jumpTo = () => {
  router.push({ path: '/serviceCenter/appStore' });
};
const provinceDataList = async () => {
  const { data } = await getProvince();
  localStorage.setItem('provinceDataList', JSON.stringify(data));
  const { pids, defaultPid } = settingsStore.platformInfo;
  const numbersArray = pids.split(',').map(Number); // 将字符串分割并转为数字数组
  provinceCity.value = data.filter((item) => numbersArray.includes(item.id));
  firstCity.value = provinceCity.value[0].provinceName;
  if (defaultPid) {
    defaultProvince.value = provinceCity.value.filter(
      (item) => item.id == defaultPid
    );
  }
};
function accountLists() {
  accountList(pageData.value).then((res) => {
    max_account_num.value = res.data.max_account_num;
    freeNum.value = res.data.freeNum;
  });
}
const closeIcon = () => {
  clearInterval(pollingInterval);
};
// 续费
const renewBtn = async () => {
  if (groupId == 0) {
    router.push({
      path: '/serviceCenter/appDetail',
      query: {
        id: settingsStore.platformInfo.appId,
        type: 'renew',
        category: '续费',
      },
    });
  } else {
    dialogTableVisible.value = true;
    imgLoading.value = true;
    const data = await codeRenewalApi();
    if (data.code == 20000) {
      code_url.value = '';
      out_trade_no.value = data.data.out_trade_no;
      QRCode.toDataURL(data.data.code_url)
        .then((url) => {
          code_url.value = url;
          timeRemaining.value = 300; // 重置倒计时
          startCountdown(); // 开始倒计时
          startPolling(); // 开始轮询
          imgLoading.value = false;
        })
        .catch((error) => {
          console.error('二维码生成失败:', error);
        });
    }
  }
};
// 倒计时格式化为分钟和秒
const formattedTime = computed(() => {
  const minutes = Math.floor(timeRemaining.value / 60);
  const seconds = timeRemaining.value % 60;
  return (
    '请在' +
    `${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}` +
    '秒内完成支付'
  );
});
// 倒计时逻辑
let countdownInterval;
const startCountdown = () => {
  clearInterval(countdownInterval); // 清除之前的倒计时
  countdownInterval = setInterval(() => {
    if (timeRemaining.value > 0) {
      timeRemaining.value -= 1;
    } else {
      clearInterval(countdownInterval); // 倒计时结束时停止计时
      stopPolling(); // 停止轮询
    }
  }, 1000);
};

// 轮询支付状态逻辑
let pollingInterval;
const startPolling = () => {
  clearInterval(pollingInterval); // 清除之前的轮询
  pollingInterval = setInterval(async () => {
    const response = await channelRenewalVertiyApi({
      out_trade_no: out_trade_no.value,
    }); // 模拟后端请求
    if (response.msg === '续费成功') {
      paymentStatus.value = '购买成功';
      clearInterval(pollingInterval); // 停止轮询
      clearInterval(countdownInterval); // 停止倒计时
      dialogTableVisible.value = false;
      getInfo();
      ElMessage({
        message: response.msg,
        type: 'success',
      });
    }
  }, 5000); // 每 5 秒轮询一次
};

// 停止轮询
const stopPolling = () => {
  clearInterval(pollingInterval);
};
onMounted(() => {
  //获取省份
  provinceDataList();
  accountLists();
  getUserMoney();
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
